package com.adee.netty.inboundhandlerandoutboundhandler;

import io.netty.bootstrap.Bootstrap;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.util.CharsetUtil;

public class MyClient {
    public static void main(String[] args) {
        EventLoopGroup group = new NioEventLoopGroup(1);
        try {
            Bootstrap bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            ChannelPipeline p = ch.pipeline();
                            p.addLast(new MyByteToLongDecoder()); // 入栈解码器
                            p.addLast(new MyLongToByteEncoder()); // 出栈编码器
                            p.addLast(new SimpleChannelInboundHandler<Long>() {
                                @Override
                                public void channelActive(ChannelHandlerContext ctx) throws Exception {
                                    // 发送的数据是long类型时，就会先回调上面MessageToByteEncoder.encode方法，否则不回调
                                    ctx.channel().writeAndFlush(100000000000L); // 回调上面MessageToByteEncoder.encode
                                    ctx.channel().writeAndFlush(
                                            Unpooled.copiedBuffer("abcdefg", CharsetUtil.UTF_8));

                                    ctx.channel().writeAndFlush(
                                            Unpooled.copiedBuffer("g", CharsetUtil.UTF_8));
                                }

                                @Override
                                protected void channelRead0(ChannelHandlerContext ctx, Long msg) throws Exception {
                                    System.out.println(msg);
                                }
                            });
                        }
                    });
            ChannelFuture f = bootstrap.connect("127.0.0.1", 7000).sync();
            f.channel().closeFuture().sync();
        }catch (Exception e) {
            e.printStackTrace();
        } finally {
            group.shutdownGracefully();
        }
    }
}
